package com.fs.sys.web;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fs.common.annotations.Log;
import com.fs.common.bean.LogType;
import com.fs.common.bean.UserContext;
import com.fs.common.bean.UserContextHolder;
import com.fs.common.exception.ForbiddenException;
import com.fs.common.exception.UnauthorizedException;
import com.fs.sys.bean.dto.UserDTO;
import com.fs.sys.bean.dto.UserLoginDTO;
import com.fs.sys.bean.query.NoRoleUserQuery;
import com.fs.sys.bean.query.UserQuery;
import com.fs.sys.bean.req.PwdUpdateReq;
import com.fs.sys.bean.req.UserAddReq;
import com.fs.sys.bean.req.UserUpdateReq;
import com.fs.sys.bean.resp.UserPhoneCheckResp;
import com.fs.sys.service.TenantUserService;
import com.fs.sys.service.UserService;
import com.fs.sys.entityservice.UserEntityService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.security.PermitAll;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户控制器
 *
 * @author 不空军 2023/12/27 15:03
 **/
@RestController
@RequestMapping("/sys/user")
@Slf4j
@Tag(name = "用户控制器")
public class UserController {
    @Autowired
    private UserEntityService userEntityService;

    @Autowired
    private UserService userService;

    @Autowired
    private TenantUserService tenantUserService;

    @PostMapping("add")
    @Operation(summary = "新增")
    @Log(value = "用户", op = LogType.NEW)
    public void add(@RequestBody @Validated UserAddReq req) {
        String tenantId = UserContextHolder.getTenantIdOrThrow();

        UserDTO dto = new UserDTO();
        BeanUtils.copyProperties(req, dto);
        userService.insert(tenantId, dto, req.getRoleIds());
    }

    @PutMapping("update")
    @Operation(summary = "更新")
    @Log(value = "用户", op = LogType.EDIT)
    public void update(@RequestBody @Validated UserUpdateReq req) {
        String tenantId = UserContextHolder.getTenantIdOrThrow();
        UserDTO dto = new UserDTO();
        BeanUtils.copyProperties(req, dto);
        userService.update(tenantId, dto, req.getRoleIds());
    }

    @DeleteMapping("delete/{id}")
    @Operation(summary = "删除")
    @Log(value = "用户", op = LogType.DELETE)
    public void delete(@PathVariable("id") String id) {
        String tenantId = UserContextHolder.getTenantIdOrThrow();
        userService.delete(tenantId, id);
    }

    /**
     * 重置指定用户密码
     *
     * @param userId 用户id
     */
    @GetMapping("reset-pwd")
    public void resetPwd(String userId,
                         @RequestParam(value = "password", required = false) String pwd) {
        // 只有超管可以操作
        UserContext userContext = UserContextHolder.get().orElseThrow(UnauthorizedException::new);
        if (!userContext.getIsSuperAdmin()) {
            throw new ForbiddenException();
        }

        userService.resetPwd(userId, pwd);
    }

    /**
     * 通过手机号重置密码
     * @param phone 手机号
     * @param password 新密码
     * @param code 短信验证码
     */
    @GetMapping("reset-by-phone")
    @PermitAll
    public void resetPwdByPhone(String phone, String password, String code) {
        userService.resetPwdByPhone(phone, password, code);
    }

    @PostMapping("page-query")
    @Operation(summary = "查询-分页")
    public IPage<UserDTO> pageQuery(@RequestBody UserQuery query) {
        String tenantId = UserContextHolder.getTenantIdOrThrow();
        query.setTenantId(tenantId);
        return userEntityService.pageQuery(query);
    }

    @PostMapping("query")
    @Operation(summary = "查询")
    public List<UserDTO> query(@RequestBody UserQuery query) {
        String tenantId = UserContextHolder.getTenantIdOrThrow();
        query.setTenantId(tenantId);
        return userEntityService.query(query);
    }

    /**
     * 通过手机号查询用户
     */
    @GetMapping("check-by-phone")
    public UserPhoneCheckResp findByPhone(String phone) {
        return userService.checkByPhone(phone);
    }

    @GetMapping("info")
    @Operation(summary = "当前登录用户信息")
    public UserDTO getCurrentUserInfo() {
        String userId = UserContextHolder.getUserId().orElse("");
        if (StringUtils.isEmpty(userId)) {
            return new UserDTO();
        }
        UserDTO user = userEntityService.findById(userId).orElse(new UserDTO());
        user.setPassword(null);
        return user;
    }

    @PostMapping("update-mine")
    @Log(value = "用户", op = LogType.EDIT)
    public void updateMyInfo(@RequestBody UserUpdateReq req) {
        String userId = UserContextHolder.getUserIdOrThrow();
        UserDTO dto = new UserDTO();
        BeanUtils.copyProperties(req, dto);
        dto.setId(userId);
        userService.update(dto);
    }

    /**
     * 根据角色查用户
     */
    @GetMapping("query-by-role")
    public List<UserDTO> findByRole(String roleId) {
        return userService.getUserByRole(roleId);
    }

    @PostMapping("query-no-role")
    public IPage<UserDTO> findNoRoleUsers(@RequestBody NoRoleUserQuery query) {
        return userService.queryUserNoRole(query);
    }

    @PostMapping("update-pwd")
    @Log(value = "用户", op = LogType.EDIT)
    public void updatePwd(@RequestBody @Validated PwdUpdateReq req) {
        userService.updatePwd(req);
    }

    @PostMapping("online/page-query")
    public IPage<UserLoginDTO> getOnlineUsers(@RequestBody UserQuery query) {
        return userService.queryOnlineUsers(query);
    }
}
